// 1、导入http模块
const http = require("http");
const fs = require("fs");
const path = require("path");

const mime = {
  html: "text/html",
  css: "text/css",
  js: "text/javascript",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  png: "image/png",
  gif: "image/gif",
  ico: "image/x-icon",
  json: "application/json",
};

// 2、创建一个HTTP服务
const server = http.createServer((req, res) => {
  // 获取请求url的路径
  let { pathname } = new URL(req.url, "http://127.0.0.1");
  console.log(pathname, "pathname"); // /index.html  /css/index.css  /images/bg.jpg
  // 拼接文件路径
  let filePath = `${__dirname}/page${pathname}`;
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.statusCode = 404;
      res.end("<h1>404 Not Found</h1>");
      return;
    }
    // path.extname获取路径的扩展名
    let ext = path.extname(pathname).slice(1);
    console.log(ext);
    let type = mime[ext];
    if (type) {
      res.setHeader("Content-Type", `${type};charset=utf-8`);
    } else {
      res.setHeader("Content-Type", "application/octet-stream");
    }
    res.end(data);
  });
});

// 3、监听端口，启动服务
// http默认端口是80 https默认端口是443
// http://localhost:3000/search?keyword=123
server.listen(3000, () => {
  console.log("服务启动成功，端口号为：3000");
});
